package com.rookie.shiro.module.util;

import com.rookie.shiro.module.constant.SecurityConstant;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author rookie
 */
public class WebUtils {

    public static void errorJson(String json, ServletResponse response){
        if (json == null){
            json = "";
        }
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        PrintWriter out = null;
        try {
            httpServletResponse.setContentType("application/json; charset=utf-8");
            ServletOutputStream output = httpServletResponse.getOutputStream();
            output.write(json.getBytes());
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取请求的token
     */
    public static String getToken(ServletRequest httpRequest) {
        HttpServletRequest request = (HttpServletRequest) httpRequest;
        // 从header中获取token
        String token = request.getHeader(SecurityConstant.TOKEN_AUTHENTICATION_NAME);
        // 如果header中不存在token，则从参数中获取token
        if (StringUtils.isEmpty(token)) {
            token = httpRequest.getParameter(SecurityConstant.TOKEN_AUTHENTICATION_NAME);
        }
        return token;
    }
}
